<template>
  <div class="p-2">
    <!-- 除险加固管理 -->
    <!-- 查询表单 -->
    <el-card shadow="hover" style="margin-bottom: 8px">
      <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="100px">
        <el-form-item label="水库名称" prop="reservoirName">
          <el-input v-model="queryParams.reservoirName" placeholder="请输入水库名称" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="项目类型" prop="projectType">
          <el-select v-model="queryParams.projectType" placeholder="请选择项目类型" clearable style="width: 150px">
            <el-option label="全部" value="" />
            <el-option label="大坝加固" value="dam-reinforcement" />
            <el-option label="溢洪道改造" value="spillway-renovation" />
            <el-option label="输水设施" value="water-conveyance" />
            <el-option label="监测设施" value="monitoring-facility" />
            <el-option label="其他工程" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="项目状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 120px">
            <el-option label="全部" value="" />
            <el-option label="规划中" value="planning" />
            <el-option label="设计中" value="designing" />
            <el-option label="施工中" value="construction" />
            <el-option label="已完成" value="completed" />
            <el-option label="已暂停" value="paused" />
          </el-select>
        </el-form-item>
        <el-form-item label="开工时间" prop="startDate">
          <el-date-picker
            v-model="queryParams.startDate"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <el-card shadow="hover" style="margin-bottom: 8px">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="Plus" @click="handleAdd">新增项目</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete">删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 数据表格 -->
    <el-card shadow="hover">
      <el-table v-loading="loading" :data="reinforcementList" @selection-change="handleSelectionChange" border>
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="项目编号" prop="projectCode" width="120" align="center" />
        <el-table-column label="水库名称" prop="reservoirName" width="150" align="center" />
        <el-table-column label="项目名称" prop="projectName" min-width="200" show-overflow-tooltip />
        <el-table-column label="项目类型" prop="projectType" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="getProjectTypeTagStyle(row.projectType)">
              {{ getProjectTypeLabel(row.projectType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="开工时间" prop="startDate" width="120" align="center" />
        <el-table-column label="完工时间" prop="endDate" width="120" align="center" />
        <el-table-column label="项目状态" prop="status" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusTagStyle(row.status)">
              {{ getStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="投资金额" prop="investment" width="120" align="center">
          <template #default="{ row }">
            {{ formatMoney(row.investment) }}
          </template>
        </el-table-column>
        <el-table-column label="施工单位" prop="contractor" width="150" align="center" />
        <el-table-column label="操作" align="center" width="240" class-name="small-padding fixed-width" fixed="right">
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button link type="primary" icon="View" @click="handleView(scope.row)">查看</el-button>
            <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-section">
        <Pagination
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="handlePagination"
        />
      </div>
    </el-card>

    <!-- 项目表单弹窗 -->
    <ReinforcementFormDialog v-model="formDialogVisible" :title="formDialogTitle" :project-data="currentProjectData"
      @success="handleFormSuccess" />
  </div>
</template>

<script setup lang="ts" name="Reinforcement">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import { Search, Refresh, Plus, Delete, Download, Edit, View } from '@element-plus/icons-vue'
import ReinforcementFormDialog from './components/ReinforcementFormDialog.vue'
import Pagination from '@/components/Pagination/index.vue'

// 模拟API接口
const allData = ref<any[]>([])
const randInt = (min: number, max: number) => Math.floor(Math.random() * (max - min + 1)) + min
const randomChoice = <T>(arr: T[]) => arr[Math.floor(Math.random() * arr.length)]

const generateMockData = (count: number) => {
  const reservoirs = ['东圳水库', '金钟水库', '西音水库', '木兰陂水库', '青山水库']
  const types = ['dam-reinforcement', 'spillway-renovation', 'water-conveyance', 'monitoring-facility', 'other']
  const statuses = ['planning', 'designing', 'construction', 'completed', 'paused']
  const contractors = ['水利建设集团', '省水利工程公司', '智能监测科技公司', '市政工程公司']
  const names = ['大坝加固工程', '溢洪道改造项目', '输水管线改造', '监测设施升级']
  const today = new Date()
  const data: any[] = []
  for (let i = 1; i <= count; i++) {
    const start = new Date(today.getTime() - randInt(0, 180) * 24 * 3600 * 1000)
    const end = new Date(start.getTime() + randInt(30, 180) * 24 * 3600 * 1000)
    const startStr = `${start.getFullYear()}-${String(start.getMonth() + 1).padStart(2, '0')}-${String(start.getDate()).padStart(2, '0')}`
    const endStr = `${end.getFullYear()}-${String(end.getMonth() + 1).padStart(2, '0')}-${String(end.getDate()).padStart(2, '0')}`
    const type = randomChoice(types)
    const status = randomChoice(statuses)
    data.push({
      id: i,
      projectCode: `CX${String(i).padStart(3, '0')}`,
      reservoirName: randomChoice(reservoirs),
      projectName: randomChoice(names),
      projectType: type,
      startDate: startStr,
      endDate: endStr,
      status,
      investment: randInt(500000, 8000000),
      contractor: randomChoice(contractors),
      progress: status === 'completed' ? 100 : randInt(0, 99),
      description: '模拟工程描述'
    })
  }
  return data
}

const applyFiltersAndPaginate = (params: any) => {
  let filtered = allData.value.slice()
  if (params.reservoirName) {
    const kw = String(params.reservoirName).trim()
    filtered = filtered.filter((i: any) => String(i.reservoirName).includes(kw))
  }
  if (params.projectType) {
    filtered = filtered.filter((i: any) => i.projectType === params.projectType)
  }
  if (params.status) {
    filtered = filtered.filter((i: any) => i.status === params.status)
  }
  if (Array.isArray(params.startDate) && params.startDate.length === 2 && params.startDate[0] && params.startDate[1]) {
    const [start, end] = params.startDate
    const s = new Date(start).getTime()
    const e = new Date(end).getTime()
    filtered = filtered.filter((i: any) => {
      const t = new Date(i.startDate).getTime()
      return t >= s && t <= e
    })
  }
  const total = filtered.length
  const startIndex = (params.pageNum - 1) * params.pageSize
  const rows = filtered.slice(startIndex, startIndex + params.pageSize)
  return { rows, total }
}

const getReinforcementList = async (params: any) => {
  if (!allData.value.length) {
    allData.value = generateMockData(randInt(10, 50))
  }
  const { rows, total } = applyFiltersAndPaginate(params)
  return { code: 200, rows, total }
}

const deleteReinforcement = async (ids: string) => {
  const idArr = ids.split(',').map(id => Number(id))
  allData.value = allData.value.filter((item: any) => !idArr.includes(Number(item.id)))
  return { code: 200, msg: '删除成功' }
}

const exportReinforcement = async (params: any) => {
  return new Blob(['模拟导出数据'], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
}

// 响应式数据
const loading = ref(false)
const total = ref(0)
const multipleSelection = ref<any[]>([])
const reinforcementList = ref([])

// 弹窗相关
const formDialogVisible = ref(false)
const formDialogTitle = ref('新增项目')
const currentProjectData = ref<any | null>(null)

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  reservoirName: '',
  projectType: '',
  status: '',
  startDate: null
})

// 获取项目类型标签样式
const getProjectTypeTagStyle = (type: string) => {
  const styleMap: Record<string, string> = {
    'dam-reinforcement': 'danger',
    'spillway-renovation': 'warning',
    'water-conveyance': 'primary',
    'monitoring-facility': 'success',
    'other': 'info'
  }
  return styleMap[type] || 'info'
}

// 获取项目类型标签文本
const getProjectTypeLabel = (type: string) => {
  const labelMap: Record<string, string> = {
    'dam-reinforcement': '大坝加固',
    'spillway-renovation': '溢洪道改造',
    'water-conveyance': '输水设施',
    'monitoring-facility': '监测设施',
    'other': '其他工程'
  }
  return labelMap[type] || type
}

// 获取状态标签样式
const getStatusTagStyle = (status: string) => {
  const styleMap: Record<string, string> = {
    planning: 'info',
    designing: 'primary',
    construction: 'warning',
    completed: 'success',
    paused: 'danger'
  }
  return styleMap[status] || 'info'
}

// 获取状态标签文本
const getStatusLabel = (status: string) => {
  const labelMap: Record<string, string> = {
    planning: '规划中',
    designing: '设计中',
    construction: '施工中',
    completed: '已完成',
    paused: '已暂停'
  }
  return labelMap[status] || status
}

// 格式化金额
const formatMoney = (amount: number) => {
  if (!amount) return '0'
  return (amount / 10000).toFixed(1) + '万元'
}

// 查询项目列表
const getList = async () => {
  try {
    loading.value = true
    const response = await getReinforcementList(queryParams)
    reinforcementList.value = response.rows
    total.value = response.total
  } catch (error) {
    console.error('获取项目列表失败:', error)
    ElMessage.error('获取项目列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置
const resetQuery = () => {
  queryParams.reservoirName = ''
  queryParams.projectType = ''
  queryParams.status = ''
  queryParams.startDate = null
  handleQuery()
}

// 多选框选中数据
const handleSelectionChange = (selection: any[]) => {
  multipleSelection.value = selection
}

// 计算属性
const multiple = computed(() => multipleSelection.value.length === 0)

// 新增按钮操作
const handleAdd = () => {
  formDialogTitle.value = '新增项目'
  currentProjectData.value = null
  formDialogVisible.value = true
}

// 编辑项目
const handleEdit = (row: any) => {
  formDialogTitle.value = '修改项目'
  currentProjectData.value = row
  formDialogVisible.value = true
}

// 查看项目
const handleView = (row: any) => {
  formDialogTitle.value = '查看项目详情'
  currentProjectData.value = row
  formDialogVisible.value = true
}

// 删除按钮操作
const handleDelete = async (row?: any) => {
  const projectsToDelete = row ? [row] : multipleSelection.value
  if (projectsToDelete.length === 0) {
    ElMessage.warning('请选择要删除的项目记录')
    return
  }

  const projectIds = projectsToDelete.map(item => item.id)
  const projectCodes = projectsToDelete.map(item => item.projectCode).join('、')

  try {
    await ElMessageBox.confirm(
      `是否确认删除项目记录"${projectCodes}"？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await deleteReinforcement(projectIds.join(','))
    ElMessage.success('删除成功')
    multipleSelection.value = []
    getList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 导出按钮操作
const handleExport = async () => {
  const downloadLoadingInstance = ElLoading.service({ text: '正在导出数据，请稍候', background: 'rgba(0, 0, 0, 0.7)' })
  try {
    const projectsToExport = multipleSelection.value.length > 0 ? multipleSelection.value : null
    const exportData = projectsToExport ? {
      projectIds: projectsToExport.map(item => item.id)
    } : queryParams

    const response = await exportReinforcement(exportData)
    
    const isBlob = response.type !== 'application/json'
    if (isBlob) {
      const now = new Date()
      const timestamp = now.getFullYear() + 
        String(now.getMonth() + 1).padStart(2, '0') + 
        String(now.getDate()).padStart(2, '0') + 
        String(now.getHours()).padStart(2, '0') + 
        String(now.getMinutes()).padStart(2, '0') + 
        String(now.getSeconds()).padStart(2, '0')
      const filename = `除险加固项目列表_${timestamp}.xlsx`
      
      const blob = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = filename
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url)
      
      ElMessage.success('导出成功')
    } else {
      ElMessage.error('导出失败')
    }
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  } finally {
    downloadLoadingInstance.close()
  }
}

// 分页处理
const handlePagination = () => {
  getList()
}

// 表单成功回调
const handleFormSuccess = () => {
  formDialogVisible.value = false
  getList()
}

// 页面加载时获取数据
onMounted(() => {
  getList()
})
</script>

<style scoped>

</style>